<template>
  <div class="role-management">
    <el-card>
      <div class="header-actions">
        <h2>角色管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增角色
        </el-button>
      </div>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
            v-model="searchKeyword"
            placeholder="请输入角色名称搜索"
            clearable
            style="width: 300px;"
            @keyup.enter="getRoleList"
        >
          <template #append>
            <el-button @click="getRoleList" icon="Search" />
          </template>
        </el-input>
      </div>

      <!-- 角色列表 -->
      <el-table
          :data="roleList"
          border
          style="width: 100%; margin-top: 15px;"
          v-loading="loading"
      >
        <el-table-column prop="id" label="角色ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="dataScope" label="数据权限">
          <template #default="scope">
            <!-- 数据权限值映射（根据实际业务调整） -->
            <span v-if="scope.row.dataScope === 1">全部数据</span>
            <span v-if="scope.row.dataScope === 2">本部门数据</span>
            <span v-if="scope.row.dataScope === 3">本人数据</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="handleDetail(scope.row.id)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
            <el-button size="small" type="success" @click="handleAssignAcl(scope.row)">分配权限</el-button>
            <el-popconfirm
                title="确定要删除该角色吗？"
                @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单弹窗（新增/编辑） -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑角色' : '新增角色'"
        width="500px"
    >
      <el-form
          :model="formData"
          ref="roleForm"
          label-width="100px"
          :rules="formRules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编码" :disabled="isEditMode" />
        </el-form-item>
        <!-- 新增：数据权限选择项 -->
        <el-form-item label="数据权限" prop="dataScope">
          <el-select v-model="formData.dataScope" placeholder="请选择数据权限">
            <el-option label="全部数据" value="1" />
            <el-option label="本部门数据" value="2" />
            <el-option label="本人数据" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
              v-model="formData.description"
              placeholder="请输入角色描述"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限分配弹窗 -->
    <el-dialog
        v-model="aclDialogVisible"
        title="分配权限"
        width="600px"
    >
      <el-form :model="aclForm" ref="aclFormRef" label-width="100px" :rules="aclRules">
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model="aclForm.roleId" disabled />
        </el-form-item>
        <el-form-item label="权限ID列表" prop="aclIdList">
          <el-input
              v-model="aclForm.aclIdList"
              type="textarea"
              :rows="6"
              placeholder="请输入JSON格式的权限ID数组，例如：[1,2,3,4]"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="aclDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAcl">保存权限</el-button>
      </template>
    </el-dialog>

    <!-- 角色详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="角色详情"
        width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="角色ID">{{ roleDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="角色名称">{{ roleDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="角色编码">{{ roleDetail.code }}</el-descriptions-item>
        <el-descriptions-item label="数据权限">
          <span v-if="roleDetail.dataScope === 1">全部数据</span>
          <span v-if="roleDetail.dataScope === 2">本部门数据</span>
          <span v-if="roleDetail.dataScope === 3">本人数据</span>
        </el-descriptions-item>
        <el-descriptions-item label="角色描述">{{ roleDetail.description }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ roleDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="拥有权限">
          <el-tag v-for="menu in roleDetail.menus" :key="menu.id" size="small" style="margin-right: 5px">
            {{ menu.name }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { RoleApi } from '@/api/role.js'
import { MenuApi } from '@/api/menu.js'

// 角色列表数据
const roleList = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const aclDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEditMode = ref(false)
const submitLoading = ref(false)

// 当前操作的角色ID
const currentRoleId = ref(null)

// 表单数据（新增dataScope字段）
const formData = reactive({
  id: '',
  name: '',
  code: '',
  dataScope: null, // 数据权限（1:全部, 2:本部门, 3:本人）
  description: ''
})

// 角色详情
const roleDetail = ref({})

// 表单验证规则（新增dataScope验证）
const formRules = reactive({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_]+$/, message: '角色编码只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  dataScope: [
    { required: true, message: '请选择数据权限', trigger: 'change' }
  ]
})

// 表单引用
const roleForm = ref(null)

// 菜单树相关
const menuTree = ref([])
const menuTreeRef = ref(null)
const checkedMenuIds = ref([])
const treeProps = {
  label: 'name',
  children: 'children'
}

// 获取角色列表
const getRoleList = async () => {
  try {
    loading.value = true
    const result = await RoleApi.getRoleList()
    roleList.value = result.data
    pagination.total = result.data.length // 实际项目中应从接口获取总条数
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error(error.message || '获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取菜单树
const getMenuTree = async () => {
  try {
    const result = await MenuApi.getMenuTree()
    menuTree.value = result.data
  } catch (error) {
    console.error('获取菜单树失败:', error)
    ElMessage.error(error.message || '获取菜单树失败')
  }
}

// 获取角色详情
const getRoleDetail = async (id) => {
  try {
    loading.value = true
    const result = await RoleApi.getRoleDetail(id)
    roleDetail.value = result.data
    return result.data
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error(error.message || '获取角色详情失败')
  } finally {
    loading.value = false
  }
}

// 新增角色
const handleAdd = () => {
  isEditMode.value = false
  // 重置表单数据（包含dataScope）
  Object.assign(formData, {
    id: '',
    name: '',
    code: '',
    dataScope: null,
    description: ''
  })
  dialogVisible.value = true
  nextTick(() => {
    roleForm.value?.resetFields()
  })
}

// 编辑角色（回显dataScope）
const handleEdit = async (id) => {
  try {
    isEditMode.value = true
    currentRoleId.value = id
    const detail = await getRoleDetail(id)

    // 填充表单数据（包含dataScope）
    Object.assign(formData, {
      id: detail.id,
      name: detail.name,
      code: detail.code,
      dataScope: detail.dataScope, // 回显数据权限
      description: detail.description || ''
    })

    dialogVisible.value = true
    nextTick(() => {
      roleForm.value?.clearValidate()
    })
  } catch (error) {
    console.error('编辑角色失败:', error)
  }
}

// 查看角色详情
const handleDetail = async (id) => {
  await getRoleDetail(id)
  detailDialogVisible.value = true
}


// 权限分配表单数据
const aclForm = reactive({
  roleId: '',
  aclIdList: ''
})

// 权限分配表单验证规则
const aclRules = reactive({
  roleId: [
    { required: true, message: '角色ID不能为空', trigger: 'blur' }
  ],
  aclIdList: [
    { required: true, message: '请输入权限ID列表', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        try {
          const arr = JSON.parse(value)
          if (!Array.isArray(arr)) {
            callback(new Error('请输入数组格式'))
          } else if (!arr.every(item => Number.isInteger(item))) {
            callback(new Error('数组元素必须为整数'))
          } else {
            callback()
          }
        } catch (e) {
          callback(new Error('请输入有效的JSON数组'))
        }
      },
      trigger: 'blur'
    }
  ]
})

const aclFormRef = ref(null)

// 分配权限 - 修改为仅记录角色ID
const handleAssignAcl = (role) => {
  currentRoleId.value = role.id
  // 初始化表单数据
  aclForm.roleId = role.id
  aclForm.aclIdList = ''
  aclDialogVisible.value = true
}

// 保存权限分配 - 修改为解析输入的JSON数组
const handleSaveAcl = async () => {
  if (!aclForm.roleId) return

  try {
    // 表单验证
    await aclFormRef.value.validate()

    // 解析JSON数组
    const aclIdList = JSON.parse(aclForm.aclIdList)

    await RoleApi.assignAcl({
      roleId: aclForm.roleId,
      aclIdList: aclIdList
    })
    ElMessage.success('权限分配成功')
    aclDialogVisible.value = false
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error(
        error.message ||
        (error.name === 'ValidationError' ? '输入格式不正确' : '保存权限失败')
    )
  }
}

// 提交表单（创建/更新角色）
const handleSubmit = async () => {
  await roleForm.value.validate()
  submitLoading.value = true

  try {
    if (isEditMode.value) {
      await RoleApi.updateRole(formData)
      ElMessage.success('角色更新成功')
    } else {
      await RoleApi.createRole(formData)
      ElMessage.success('角色创建成功')
    }
    dialogVisible.value = false
    getRoleList() // 刷新列表
  } catch (error) {
    const errorMsg = error?.message || (isEditMode.value ? '角色更新失败' : '角色创建失败')
    ElMessage.error(errorMsg)
    console.error(errorMsg, error)
  } finally {
    submitLoading.value = false
  }
}

// 删除角色
const handleDelete = async (id) => {
  try {
    await RoleApi.deleteRole(id)
    ElMessage.success('角色删除成功')
    getRoleList() // 刷新列表
  } catch (error) {
    console.error('角色删除失败:', error)
    ElMessage.error(error.message || '角色删除失败')
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getRoleList()
}

const handleCurrentChange = (val) => {
  pagination.pageNum = val
  getRoleList()
}

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
  const timer = setTimeout(() => {
    getRoleList()
  }, 500)
  return () => clearTimeout(timer)
})

// 页面挂载时加载数据
onMounted(() => {
  getRoleList()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.acl-tree-container {
  max-height: 400px;
  overflow-y: auto;
}
</style>